<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once(BASEPATH.'../fuman/ebay/keys.php');
require_once(BASEPATH.'../fuman/ebay/eBaySession.php');

/*******************
***  同步店铺消息
**********/
class EbayMessageApi{
	
    public $ebay_api_url = 'https://api.ebay.com/ws/api.dll';
	function __construct(){    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
       $this->CI->load->library('Amazondata');
	}
    
    public function test(){
        echo 'in testhere';
    }
    
    public function apiCallMessage($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$shopid){
        $serverUrl=$this->ebay_api_url;
        $verb = 'GetMyMessages';
       	$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-3600*24*1);//3600*96*1
        $CreateTimeTo = gmdate("Y-m-d\TH:i:s");
        echo $CreateTimeFrom."----".$CreateTimeTo."<br />";
        $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
        $requestXmlBody .= '<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
        $requestXmlBody .= '<DetailLevel>ReturnHeaders</DetailLevel>';
        $requestXmlBody .= "<StartTime>$CreateTimeFrom</StartTime><EndTime>$CreateTimeTo</EndTime>";
        $requestXmlBody .= "<Pagination><EntriesPerPage>10</EntriesPerPage>";
        $requestXmlBody .= "<PageNumber>1</PageNumber></Pagination>";
        $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
        $requestXmlBody .= '</GetMyMessagesRequest>';
        $session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
        $responseXml = $session->sendHttpRequest($requestXmlBody);
        //dump($requestXmlBody);
       // dump($responseXml);
        $import_msg_ids=$this->saveMessages($responseXml,$shopid);
        if(count($import_msg_ids)>0){
            $import_msg_ids=$this->importMessageDetail($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$import_msg_ids);    
        }
        return $import_msg_ids;
    }
    
    public function saveMessages($messageXml,$shopid){
        $ret_ids=array();//导入的数据
        $xml=simplexml_load_string($messageXml);
        $data = json_decode(json_encode($xml),TRUE);
        //dump($data);
        if(!isset($data['Messages']['Message'])) return 0;
        $leng=count($data['Messages']);
        //$firstSender=$data['Messages']['Message']["Sender"];
        if(isset($data['Messages']['Message']["Sender"])){
            $messages[]=$data['Messages']['Message'];    
        }else{
            $messages=$data['Messages']['Message'];
        }
        for ($i=0; $i < count($messages);$i++) {
            
            $msginfo=$messages[$i];
            //dump($msginfo);
            
            $Replied=$msginfo['Replied']=="false"?0:1;
            $Read=$msginfo['Read']=="false"?0:1;
            if(!isset($msginfo['ExternalMessageID'])){
                $msginfo['ExternalMessageID']='';    
            }
            $senduserid=isset($msginfo['SendingUserID'])?$msginfo['SendingUserID']:0;
            $itemid=isset($msginfo['ItemID'])?$msginfo['ItemID']:'';
            $messagetype=isset($msginfo['MessageType'])?$msginfo['MessageType']:'tips';
            $into=array("Sender"=>$msginfo['Sender'],"SendToName"=>$msginfo['RecipientUserID'],"Subject"=>$msginfo['Subject'],
            "MessageID"=>$msginfo['MessageID'],'ExternalMessageID'=>$msginfo['ExternalMessageID'],
            "Read"=>$Read,"Replied"=>$Replied,"ReceiveDate"=>date("Y-m-d H:i:s",strtotime($msginfo['ReceiveDate'])),'shop_id'=>$shopid,
            "MessageType"=>$messagetype,'ItemID'=>$itemid,"SendingUserID"=>$senduserid);
            $into['ImportTime']=date("Y-m-d H:i:s");
            //dump($into);
            $sql_message = "SELECT * FROM db_ebaymessage WHERE MessageID = '{$into['MessageID']}'";
			$haves_import = $this->db1->query($sql_message)->row_array();
			if($haves_import){
			    echo "messageid:{$into['MessageID']} haves existed,jump it<br />"; 
				continue;
			}
            $insertid=$this->db1->insert("db_ebaymessage",$into);
            echo "add message messageid:{$into['MessageID']} success<br />";
            $ret_ids[]=$into['MessageID'];
        }
        return $ret_ids;
    }
    
    
    public function importMessageDetail($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$messageids){
        $detailMessageXml=$this->apiCallMessageDetail($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$messageids);
        //dump($messageids);
        $ret_ids=array();//导入的数据
        $xml=simplexml_load_string($detailMessageXml);
        $data = json_decode(json_encode($xml),TRUE);
        //dump($data);
        if(!isset($data['Messages']['Message'])) return 0;
        $messages=array();
        if(count($messageids)<2){
            $messages[]=$data['Messages']['Message'];    
        }else{
            $messages=$data['Messages']['Message'];
        }
        //echo 'themessages info:';
       // dump($messages);
        $leng=count($messages);
        for ($i=0; $i < count($messages);$i++) { 
            $msginfo=$messages[$i];
            $into=array("MessageID"=>$msginfo['MessageID'],"Text"=>$msginfo['Text']);
            $sql_message = "SELECT * FROM db_ebaymessage_detail WHERE MessageID = '{$into['MessageID']}'";
			$haves_import = $this->db1->query($sql_message)->row_array();
			if($haves_import){
				continue;
			}
            $insertid=$this->db1->insert("db_ebaymessage_detail",$into);
            //echo "add messageDetail messageid:{$into['MessageID']} success<br />";
            $ret_ids[]=$into['MessageID'];
        }
        return $ret_ids;
    }

    public function apiCallMessageDetail($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$messageids){
        $serverUrl=$this->ebay_api_url;
        $verb = 'GetMyMessages';
       	$CreateTimeFrom = gmdate("Y-m-d\TH:i:s",time()-3600*48*1);
        $CreateTimeTo = gmdate("Y-m-d\TH:i:s");
        $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
        $requestXmlBody .= '<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
        $requestXmlBody .= '<DetailLevel>ReturnMessages</DetailLevel><MessageIDs>';
        for ($i=0; $i < count($messageids);$i++) { 
            $requestXmlBody .= "<MessageID>".$messageids[$i]."</MessageID>";
        }
        $requestXmlBody .= "</MessageIDs><StartTime>$CreateTimeFrom</StartTime><EndTime>$CreateTimeTo</EndTime>";
        $requestXmlBody .= "<Pagination><EntriesPerPage>10</EntriesPerPage>";
        $requestXmlBody .= "<PageNumber>1</PageNumber></Pagination>";
        $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>$userToken</eBayAuthToken></RequesterCredentials>";
        $requestXmlBody .= '</GetMyMessagesRequest>';
        $session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
        $responseXml = $session->sendHttpRequest($requestXmlBody);
        return $responseXml;
    }
    
    public function apiCallReply($userToken, $devID, $appID, $certID, $compatabilityLevel, $siteID,$replyinfo){
        $serverUrl=$this->ebay_api_url;
        $msg=$replyinfo['msg_info'];
        //dump($msg);
        $msg['Subject']=getstr($msg['Subject'],60);
        $verb = 'AddMemberMessageRTQ';
        $requestXmlBody = '<?xml version="1.0" encoding="utf-8" ?>';
        $requestXmlBody .= '<AddMemberMessageRTQRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
        $requestXmlBody .= "<RequesterCredentials><eBayAuthToken>".$userToken."</eBayAuthToken></RequesterCredentials>";
        $requestXmlBody .= "<ItemID>".$msg['itemID']."</ItemID>";
        $requestXmlBody .= '<MemberMessage>';
        $requestXmlBody .= "<Body>".$replyinfo['replyinfo']."</Body><EmailCopyToSender>false</EmailCopyToSender>";
        $requestXmlBody .= "<RecipientID>".$msg["Sender"]."</RecipientID>";
        $requestXmlBody .= "<DisplayToPublic>false</DisplayToPublic>";
        $requestXmlBody .= "<EmailCopyToSender>true</EmailCopyToSender>";
        $requestXmlBody .= "<ParentMessageID>".$msg["ExternalMessageID"]."</ParentMessageID>";
        $requestXmlBody .= "</MemberMessage>";
        $requestXmlBody .= '</AddMemberMessageRTQRequest>';
        //dump($requestXmlBody);
        $session = new eBaySession($userToken, $devID, $appID, $certID, $serverUrl, $compatabilityLevel, $siteID, $verb);
        $responseReplyXml = $session->sendHttpRequest($requestXmlBody);
        $xml=simplexml_load_string($responseReplyXml);
        $data = json_decode(json_encode($xml),TRUE);
        if(!isset($data['Errors']['ShortMessage'])){
            $errmsg=$data['Errors']['ShortMessage']='';
        }
        if($data['Ack']=='Success'){
            $savedata=array('update_online'=>1,'Replied'=>1);
            $errmsg=$data['Ack'];
            $this->db1->update('db_ebaymessage', $savedata, 'id='.$msg['id']);  
            $this->db1->update('db_ebaymessage_reply', array("update_online"=>1,'ret_msg'=>$errmsg), 'MessageID='.$msg['MessageID']);  
            $result_msg=array("state"=>'success','msg'=>'ok');
        }else{
            $errmsg=$data['Errors']['ShortMessage'];
            $savedata=array('update_online'=>2,'Replied'=>1);
            $this->db1->update('db_ebaymessage', $savedata, 'id='.$msg['id']); 
            $this->db1->update('db_ebaymessage_reply', array("update_online"=>2,'ret_msg'=>$errmsg), 'MessageID='.$msg['MessageID']);   
            $result_msg=array("state"=>'updateerror','msg'=>$errmsg);    
        }
        return $result_msg;
    }
    
    
    //修正线上信息
    public function reviseMessage(){
        /*<?xml version="1.0" encoding="utf-8"?>
<AddMemberMessageAAQToPartnerRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <!-- Call-specific Input Fields -->
  <ItemID> ItemIDType (string) </ItemID>
  <MemberMessage> MemberMessageType
    <Body> string </Body>
    <EmailCopyToSender> boolean </EmailCopyToSender>
    <MessageMedia> MessageMediaType
      <MediaName> string </MediaName>
      <MediaURL> anyURI </MediaURL>
    </MessageMedia>
    <!-- ... more MessageMedia nodes allowed here ... -->
    <QuestionType> QuestionTypeCodeType </QuestionType>
    <RecipientID> string </RecipientID>
    <!-- ... more RecipientID values allowed here ... -->
    <Subject> string </Subject>
  </MemberMessage>
  <!-- Standard Input Fields -->
  <ErrorLanguage> string </ErrorLanguage>
  <MessageID> string </MessageID>
  <Version> string </Version>
  <WarningLevel> WarningLevelCodeType </WarningLevel>
</AddMemberMessageAAQToPartnerRequest>*/
    }

}